package com.wens.baselibrary.util.system

import com.blankj.utilcode.util.AppUtils
import com.blankj.utilcode.util.CacheDiskStaticUtils
import java.util.*

object UserInfoUtil {
    fun isNewUser(): Boolean {
        val codeNumber =
            CacheDiskStaticUtils.getString("version_code_number") ?: return true
        val intCodeNumber: Int = try {
            codeNumber.toInt()
        } catch (ex: Exception) {
            -1
        }
        if (intCodeNumber == -1) {
            return true
        }
        val appVersion = AppUtils.getAppVersionCode() * 10000 //获取清单文件中versionCode节点的值
        return intCodeNumber >= appVersion
    }

    fun init() {
        recordUserLoginInformation()
        val codeNumber =
            CacheDiskStaticUtils.getString("version_code_number")
        if (codeNumber != null) {
            return
        }
        val appVersion = AppUtils.getAppVersionCode() //获取清单文件中versionCode节点的值
        if (appVersion != -1)
            CacheDiskStaticUtils.put("version_code_number", (appVersion * 10000).toString())
    }

    /**
     * 记录用户第一次登录时间
     */
    private fun recordUserFirstLogin() {
        if (CacheDiskStaticUtils.getString("first_login") == null) {
            val date = Date()
            CacheDiskStaticUtils.put("first_login", date.time.toString())
        }
    }

    /**
     * 获取用户第一次登录时间
     */
    fun getUserFirstLoginTime(): Long {
        val firstlogintime = CacheDiskStaticUtils.getString("record_user_info", "first_login")
        return firstlogintime?.toLong() ?: -1
    }

    /**
     * 记录用户最后一次登录时间
     */
    private fun recordUserLastLogin() {
        val date = Date()
        CacheDiskStaticUtils.put("last_login", date.time.toString())
    }

    /**
     * 获取用户最后一次登录时间
     */
    fun getUserLastLoginTime(): Long {
        val loginTime: String? = CacheDiskStaticUtils.getString("record_user_info", "last_login")
        return loginTime?.toLong() ?: -1
    }

    /**
     * 记录用户登录次数
     */
    fun recordUserLoginCount() {
        try {
            var count: Long = 1
            if (CacheDiskStaticUtils.getString("login_count") != null) {
                count = CacheDiskStaticUtils.getString("login_count")!!
                    .toLong() + 1
            }
            CacheDiskStaticUtils.put("login_count", count.toString())
        } catch (ignored: Throwable) {
        }
    }

    /**
     * 获取用户登录次数
     */
    fun getUserUserLoginCount(): Long {
        try {
            val loginCount = CacheDiskStaticUtils.getString("login_count")
            if (loginCount != null) {
                return loginCount.toLong()
            }
        } catch (ignored: Throwable) {
        }
        return 0
    }

    /**
     * 获取用户登录信息
     */
    private fun recordUserLoginInformation() {
        recordUserFirstLogin()
        recordUserLastLogin()
    }
}